<!DOCTYPE html>


<html lang="zh-CN">
  

    <head>
      <meta charset="utf-8" />
       
      <meta name="keywords" content="ES6、JS" />
       
      <meta name="description" content="ES6、JS" />
      
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title> 君书</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/atom.xml" title="君书" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      
<section class="cover">
    
  <div class="cover-frame">
    <div class="bg-box">
      <img src="/images/cover1.jpg" alt="image frame" />
    </div>
    <div class="cover-inner text-center text-white">
      <h1><a href="/">君书</a></h1>
      <div id="subtitle-box">
        
        <span id="subtitle"></span>
        
      </div>
      <div>
        
      </div>
    </div>
  </div>
  <div class="cover-learn-more">
    <a href="javascript:void(0)" class="anchor"><i class="ri-arrow-down-line"></i></a>
  </div>
</section>



<script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11/lib/typed.min.js"></script>


<!-- Subtitle -->

  <script>
    try {
      var typed = new Typed("#subtitle", {
        strings: ['路还这么长', '这个年纪不该忧愁万分的', '生活嘛，慢慢来，所有的好运都在路上'],
        startDelay: 0,
        typeSpeed: 200,
        loop: true,
        backSpeed: 100,
        showCursor: true
      });
    } catch (err) {
      console.log(err)
    }
  </script>
  
<div id="main">
  <section class="outer">
  
  
  

<div class="notice" style="margin-top:50px">
    <i class="ri-heart-fill"></i>
    <div class="notice-content" id="broad"></div>
</div>
<script type="text/javascript">
    fetch('https://v1.hitokoto.cn')
        .then(response => response.json())
        .then(data => {
            document.getElementById("broad").innerHTML = data.hitokoto;
        })
        .catch(console.error)
</script>

<style>
    .notice {
        padding: 20px;
        border: 1px dashed #e6e6e6;
        color: #969696;
        position: relative;
        display: inline-block;
        width: 100%;
        background: #fbfbfb50;
        border-radius: 10px;
    }

    .notice i {
        float: left;
        color: #999;
        font-size: 16px;
        padding-right: 10px;
        vertical-align: middle;
        margin-top: -2px;
    }

    .notice-content {
        display: initial;
        vertical-align: middle;
    }
</style>
  
  <article class="articles">
    
    
    
    
    <article
  id="post-探React之旅一"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2022/03/05/%E6%8E%A2React%E4%B9%8B%E6%97%85%E4%B8%80/"
    >探React之旅一</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/03/05/%E6%8E%A2React%E4%B9%8B%E6%97%85%E4%B8%80/" class="article-date">
  <time datetime="2022-03-05T03:24:16.000Z" itemprop="datePublished">2022-03-05</time>
</a>    
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <p>本次探讨的 React 版本为 16 之前的版本，由于 React 在 16 版本后底层做了重构，所以新版本和旧版本都值得我们研究（新版本后续会单独再写博探讨）。本次主要探讨以下几个问题：</p>
<ol>
<li>jsx 如何转为 vdom</li>
<li>vdom 如何转换为真实 DOM，实现页面的渲染</li>
<li>组件状态变更前后，vdom 是如何比较差异的</li>
</ol>
<p>请注意，本篇内容可能会较多。</p> 
      <a class="article-more-link" href="/2022/03/05/%E6%8E%A2React%E4%B9%8B%E6%97%85%E4%B8%80/"
        >继续阅读</a
      >
       
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/React/" rel="tag">React</a></li></ul>

    </footer>
  </div>

   
    
</article>

    
    <article
  id="post-http缓存"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2022/02/28/http%E7%BC%93%E5%AD%98/"
    >http缓存</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/02/28/http%E7%BC%93%E5%AD%98/" class="article-date">
  <time datetime="2022-02-28T08:17:08.000Z" itemprop="datePublished">2022-02-28</time>
</a>    
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <p>http 缓存是性能优化的一个方向，可以将长时间段内不会变化的资源进行缓存，缓解服务的压力，同时也可以节省请求等待时长，加快网页的渲染。</p>
<p>http 缓存分为 <code>强制缓存</code> 和 <code>协商缓存</code> 两种形式，今天通过代码描述下两种缓存的实现原理。</p> 
      <a class="article-more-link" href="/2022/02/28/http%E7%BC%93%E5%AD%98/"
        >继续阅读</a
      >
       
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" rel="tag">性能优化</a></li></ul>

    </footer>
  </div>

   
    
</article>

    
    <article
  id="post-服务端渲染react"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2022/02/28/%E6%9C%8D%E5%8A%A1%E7%AB%AF%E6%B8%B2%E6%9F%93react/"
    >同构渲染react</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/02/28/%E6%9C%8D%E5%8A%A1%E7%AB%AF%E6%B8%B2%E6%9F%93react/" class="article-date">
  <time datetime="2022-02-28T07:42:16.000Z" itemprop="datePublished">2022-02-28</time>
</a>    
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <h2 id="渲染"><a href="#渲染" class="headerlink" title="渲染"></a>渲染</h2><p>渲染即将数据和 html 进行拼接。渲染分为客户端渲染和服务端渲染，服务端渲染又可分为传统服务端渲染和同构渲染。</p> 
      <a class="article-more-link" href="/2022/02/28/%E6%9C%8D%E5%8A%A1%E7%AB%AF%E6%B8%B2%E6%9F%93react/"
        >继续阅读</a
      >
       
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/ssr/" rel="tag">ssr</a></li></ul>

    </footer>
  </div>

   
    
</article>

    
    <article
  id="post-React函数组件的hook"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2022/02/24/React%E5%87%BD%E6%95%B0%E7%BB%84%E4%BB%B6%E7%9A%84hook/"
    >React函数组件的hook</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/02/24/React%E5%87%BD%E6%95%B0%E7%BB%84%E4%BB%B6%E7%9A%84hook/" class="article-date">
  <time datetime="2022-02-24T09:38:26.000Z" itemprop="datePublished">2022-02-24</time>
</a>    
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <p>总结下最近使用的函数组件相关的 Hook。后期逐步补充实现模拟 Hook 相关的源码。</p>
<p>Hook 增强了函数组件的功能，为函数组件提供了设置组件状态、优化组件渲染等相关的函数。使得函数组件可以拥有类组件的一些特点。下面表格是汇总的一部分 Hook:</p>
<table>
<thead>
<tr>
<th align="center">方法</th>
<th align="center">功能</th>
<th align="center">含义</th>
</tr>
</thead>
<tbody><tr>
<td align="center">useState(state)</td>
<td align="center">组件可以拥有自身状态以及进行状态的设置</td>
<td align="center">缓存状态，函数组件再次渲染时，状态不会重置</td>
</tr>
<tr>
<td align="center">useCallback(callback, [dept])</td>
<td align="center">组件内可添加自定义方法，用于响应用户的操作</td>
<td align="center">缓存方法，函数组件再次渲染时，若依赖项 dept 不变化，函数不会重新生成</td>
</tr>
<tr>
<td align="center">useEffect(syncCallback, dept)</td>
<td align="center">函数的生命周期，组件的副作用</td>
<td align="center">syncCallback 中返回函数，dept 为[], 表示卸载组件时要执行；syncCallback 中未返回函数，dept 为 []，则在首次挂载完执行，若 dept 数组有值，则在值每次变化时，执行 syncCallback。需注意：<strong>syncCallback 必须是同步函数</strong></td>
</tr>
<tr>
<td align="center">useReducer(reducer, dept)</td>
<td align="center">当 dept 变化时，执行 reducer()，更新 state</td>
<td align="center">类似 useCallback</td>
</tr>
<tr>
<td align="center">useRef()</td>
<td align="center">获取组件实例或者 DOM 实例；跨生命周期缓存数据</td>
<td align="center">类似 <strong>React.createRef()</strong></td>
</tr>
<tr>
<td align="center">createContext()</td>
<td align="center">组件状态共享</td>
<td align="center">创建上下文</td>
</tr>
<tr>
<td align="center">useContext(Context)</td>
<td align="center">组件状态共享</td>
<td align="center">使用上下文</td>
</tr>
<tr>
<td align="center">useMemo(callback, dept)</td>
<td align="center">拥有计算属性</td>
<td align="center">当 dept 变化时，重新执行 callback，获取到新的值，类似 mobx 中的 @computed 修饰符功能</td>
</tr>
<tr>
<td align="center">memo(Component)</td>
<td align="center">优化组件渲染</td>
<td align="center">类似 PureComponent，可一定程度减少组件的无用渲染</td>
</tr>
</tbody></table> 
      <a class="article-more-link" href="/2022/02/24/React%E5%87%BD%E6%95%B0%E7%BB%84%E4%BB%B6%E7%9A%84hook/"
        >继续阅读</a
      >
       
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
    </footer>
  </div>

   
    
</article>

    
    <article
  id="post-常用的MIME类型"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2022/02/22/%E5%B8%B8%E7%94%A8%E7%9A%84MIME%E7%B1%BB%E5%9E%8B/"
    >常用的MIME类型</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/02/22/%E5%B8%B8%E7%94%A8%E7%9A%84MIME%E7%B1%BB%E5%9E%8B/" class="article-date">
  <time datetime="2022-02-22T01:24:04.000Z" itemprop="datePublished">2022-02-22</time>
</a>    
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <p>汇总常用的 MIME 类型：</p>
<table>
<thead>
<tr>
<th align="center">文件类型</th>
<th align="center">MIME</th>
</tr>
</thead>
<tbody><tr>
<td align="center">.doc</td>
<td align="center">application/msword</td>
</tr>
<tr>
<td align="center">.docx</td>
<td align="center">application/vnd.openxmlformats-officedocument.wordprocessingml.document</td>
</tr>
<tr>
<td align="center">.rtf</td>
<td align="center">application/rtf</td>
</tr>
<tr>
<td align="center">.xls</td>
<td align="center">application/vnd.ms-excel application/x-excel</td>
</tr>
<tr>
<td align="center">.xlsx</td>
<td align="center">application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</td>
</tr>
<tr>
<td align="center">.ppt</td>
<td align="center">application/vnd.ms-powerpoint</td>
</tr>
<tr>
<td align="center">.pptx</td>
<td align="center">application/vnd.openxmlformats-officedocument.presentationml.presentation</td>
</tr>
<tr>
<td align="center">.pps</td>
<td align="center">application/vnd.ms-powerpoint</td>
</tr>
<tr>
<td align="center">.ppsx</td>
<td align="center">application/vnd.openxmlformats-officedocument.presentationml.slideshow</td>
</tr>
<tr>
<td align="center">.pdf</td>
<td align="center">application/pdf</td>
</tr>
<tr>
<td align="center">.swf</td>
<td align="center">application/x-shockwave-flash</td>
</tr>
<tr>
<td align="center">.dll</td>
<td align="center">application/x-msdownload</td>
</tr>
<tr>
<td align="center">.exe</td>
<td align="center">application/octet-stream</td>
</tr>
<tr>
<td align="center">.msi</td>
<td align="center">application/octet-stream</td>
</tr>
<tr>
<td align="center">.chm</td>
<td align="center">application/octet-stream</td>
</tr>
<tr>
<td align="center">.cab</td>
<td align="center">application/octet-stream</td>
</tr>
<tr>
<td align="center">.ocx</td>
<td align="center">application/octet-stream</td>
</tr>
<tr>
<td align="center">.rar</td>
<td align="center">application/octet-stream</td>
</tr>
<tr>
<td align="center">.tar</td>
<td align="center">application/x-tar</td>
</tr>
<tr>
<td align="center">.tgz</td>
<td align="center">application/x-compressed</td>
</tr>
<tr>
<td align="center">.zip</td>
<td align="center">application/x-zip-compressed</td>
</tr>
<tr>
<td align="center">.z</td>
<td align="center">application/x-compress</td>
</tr>
<tr>
<td align="center">.wav</td>
<td align="center">audio/wav</td>
</tr>
<tr>
<td align="center">.wma</td>
<td align="center">audio/x-ms-wma</td>
</tr>
<tr>
<td align="center">.wmv</td>
<td align="center">video/x-ms-wmv</td>
</tr>
<tr>
<td align="center">.mp3 .mp2 .mpe .mpeg .mpg</td>
<td align="center">audio/mpeg</td>
</tr>
<tr>
<td align="center">.rm</td>
<td align="center">application/vnd.rn-realmedia</td>
</tr>
<tr>
<td align="center">.mid .midi .rmi</td>
<td align="center">audio/mid</td>
</tr>
<tr>
<td align="center">.bmp</td>
<td align="center">image/bmp</td>
</tr>
<tr>
<td align="center">.gif</td>
<td align="center">image/gif</td>
</tr>
<tr>
<td align="center">.png</td>
<td align="center">image/png</td>
</tr>
<tr>
<td align="center">.tif .tiff</td>
<td align="center">image/tiff</td>
</tr>
<tr>
<td align="center">.jpe .jpeg .jpg</td>
<td align="center">image/jpeg</td>
</tr>
<tr>
<td align="center">.txt</td>
<td align="center">text/plain</td>
</tr>
<tr>
<td align="center">.xml</td>
<td align="center">text/xml</td>
</tr>
<tr>
<td align="center">.html</td>
<td align="center">text/html</td>
</tr>
<tr>
<td align="center">.css</td>
<td align="center">text/css</td>
</tr>
<tr>
<td align="center">.js</td>
<td align="center">text/javascript</td>
</tr>
<tr>
<td align="center">.mht .mhtml</td>
<td align="center">message/rfc822</td>
</tr>
</tbody></table>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
    </footer>
  </div>

   
    
</article>

    
    <article
  id="post-React-中的生命周期"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2022/02/11/React-%E4%B8%AD%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/"
    >React 中的生命周期</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/02/11/React-%E4%B8%AD%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/" class="article-date">
  <time datetime="2022-02-11T02:30:17.000Z" itemprop="datePublished">2022-02-11</time>
</a>    
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <p>React16+ 版本中生命周期与 React15 版本相比发生了变化，本博文主要记录下 React 版本升级前后生命周期的差异。</p>
<h2 id="React-中的生命周期"><a href="#React-中的生命周期" class="headerlink" title="React 中的生命周期"></a>React 中的生命周期</h2><p>React15 中的生命周期有：</p>
<ol>
<li><p><code>componentWillMount</code> </p>
</li>
<li><p><code>componentDidMount</code></p>
<p> 组件首次挂载完成后执行该生命周期</p>
</li>
<li><p><code>componentWillReceiveProps</code></p>
<p> 父组件状态更新时，会触发子组件的这个生命周期函数。在这个生命周期内，可通过 props 派生子组件的状态等</p>
</li>
<li><p><code>shouldComponentUpdate</code></p>
<p> 可进行组件渲染的优化</p>
</li>
<li><p><code>componentWillUpdate</code></p>
</li>
<li><p><code>componentDidUpdate</code></p>
</li>
<li><p><code>componentWillUnmount</code></p>
</li>
</ol>
<p><img src="/2022/02/11/React-%E4%B8%AD%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/react15.png" alt="生命周期"></p>
<p>React16 版本的生命周期有：</p>
<ol>
<li><code>getDerivedStateFromProps</code> </li>
<li><code>componentDidMount</code></li>
<li><code>shouldComponentUpdate</code></li>
<li><code>getSnapShotBeforeUpdate</code></li>
<li><code>componentDidUpdate</code></li>
<li><code>componentWillUnmount</code></li>
</ol>
<p><img src="/2022/02/11/React-%E4%B8%AD%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/react16.png" alt="生命周期"></p>
<p>从生命周期的比对，可发现在 React16 版本中新增了<code>getDerivedStateFormProps</code> 和 <code>getSnapShotBeforeUpdate</code> 两个生命周期函数，同时将 <code>componentWillUpdate、componentWillMount 和 componentWillReceiveProps</code> 三个生命周期标记为 <code>unsafe</code>，不推荐使用。</p>
<h3 id="不推荐使用的生命周期"><a href="#不推荐使用的生命周期" class="headerlink" title="不推荐使用的生命周期"></a>不推荐使用的生命周期</h3><ol>
<li><code>componentWillUpdate、componentWillMount 和 componentWillReceiveProps</code> 生命周期的误用和滥用，会导致组件更新的死循环和不合理</li>
<li>React16 的 render 阶段使用了 Fiber 机制。所以组件在 render 阶段可能会被中断重启。重启后，组件将会重新挂载执行生命周期函数。</li>
</ol>
<p>React16 版本中 render 之前的生命周期函数主要是 <code>static getDerivedStateFromProps</code>（从 props 中获取派生 state）。该函数是个静态方法，所以内部获取不到组件实例 this，故可避免通过 <code>this.setState()</code> 方法更新组件状态造成死循环。</p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/" rel="tag">生命周期</a></li></ul>

    </footer>
  </div>

   
    
</article>

    
    <article
  id="post-项目中串并行执行命令的方式总结"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2022/01/18/%E9%A1%B9%E7%9B%AE%E4%B8%AD%E4%B8%B2%E5%B9%B6%E8%A1%8C%E6%89%A7%E8%A1%8C%E5%91%BD%E4%BB%A4%E7%9A%84%E6%96%B9%E5%BC%8F%E6%80%BB%E7%BB%93/"
    >项目中串并行执行命令的方式总结</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/01/18/%E9%A1%B9%E7%9B%AE%E4%B8%AD%E4%B8%B2%E5%B9%B6%E8%A1%8C%E6%89%A7%E8%A1%8C%E5%91%BD%E4%BB%A4%E7%9A%84%E6%96%B9%E5%BC%8F%E6%80%BB%E7%BB%93/" class="article-date">
  <time datetime="2022-01-18T09:02:52.000Z" itemprop="datePublished">2022-01-18</time>
</a>    
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <p>开发 web 项目时，为了方便开发体验，我们一般会搭建脚手架，在项目根目录的 <code>package.json</code> 文件中通过配置 <code>sripts</code> 命令，帮助项目快速运行。今天总结下如何更方便快捷的运行多个命令。</p>
<p>多个命令一起运行时，根据命令之间是否存在依赖关系分为俩类：</p>
<ol>
<li><p>串行命令（顺序执行）</p>
<p> <strong>顺序执行命令即 前面一个命令未执行结束，则后一个任务不会执行。</strong></p>
</li>
<li><p>并行命令</p>
</li>
</ol>
<p>根据命令之间的依赖关系，npm 提供了多个第三方插件帮助执行多个命令，但我们也可不借助第三方插件实现命令的执行。</p>
<h2 id="不借助插件"><a href="#不借助插件" class="headerlink" title="不借助插件"></a>不借助插件</h2><p>可按照表格中的符号将多个命令进行组合：</p>
<table>
<thead>
<tr>
<th align="center">符号</th>
<th align="center">含义</th>
</tr>
</thead>
<tbody><tr>
<td align="center">&amp;</td>
<td align="center">并行执行多条命令</td>
</tr>
<tr>
<td align="center">&amp;&amp;</td>
<td align="center">顺序执行多条命令，当前一个命令<code>出错</code>时，则不会运行后续的命令</td>
</tr>
<tr>
<td align="center">||</td>
<td align="center">顺序执行多条命令，当前一个命令<code>正确</code>时，则不会运行后续的命令</td>
</tr>
</tbody></table>
<p>示例1：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;scripts&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;dev:serials&quot;</span>: <span class="string">&quot;webpack --config webpack.client.js &amp;&amp; webpack --config webpack.server.js &amp;&amp; nodemon build/bundle.js&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;dev:parallel&quot;</span>: <span class="string">&quot;webpack --config webpack.client.js &amp; webpack --config webpack.server.js &amp; nodemon build/bundle.js&quot;</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>示例2：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;scripts&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;dev:build-server&quot;</span>: <span class="string">&quot;webpack --config webpack.server.js&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;dev:server-run&quot;</span>: <span class="string">&quot;nodemon build/bundle.js&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;dev&quot;</span>: <span class="string">&quot;webpack --config webpack.client.js &amp;&amp; npm run dev:build-server &amp;&amp; npm run dev:server-run&quot;</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="借助-npm-run-all-插件"><a href="#借助-npm-run-all-插件" class="headerlink" title="借助 npm-run-all 插件"></a>借助 <code>npm-run-all</code> 插件</h2><ol>
<li><p>并行多个命令</p>
<ol>
<li>完整写法：<code>npm-run-all --paraller dev:*</code></li>
<li>简化版1：<code>npm-run-all -p dev:*</code> </li>
<li>简化版2：<code>run-p dev:*</code>  </li>
</ol>
</li>
<li><p>串行多个命令</p>
<ol>
<li>完整写法：<code>npm-run-all --serial dev:*</code></li>
<li>简化版1： <code>npm-run-all -s dev:*</code></li>
<li>简化版2： <code>run-s dev:*</code></li>
</ol>
</li>
</ol>
<p>示例：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&quot;scripts&quot;: &#123;</span><br><span class="line">  &quot;init&quot;: &quot;run-p dev:build-*&quot;,</span><br><span class="line">  &quot;dev:build-client&quot;: &quot;webpack --config webpack.client.js&quot;,</span><br><span class="line">  &quot;dev:build-server&quot;: &quot;webpack --config webpack.server.js&quot;,</span><br><span class="line">  &quot;init:watch&quot;: &quot;run-p dev:watch-build-*&quot;,</span><br><span class="line">  &quot;dev:watch-build-client&quot;: &quot;webpack --config webpack.client.js --watch&quot;,</span><br><span class="line">  &quot;dev:watch-build-server&quot;: &quot;webpack --config webpack.server.js --watch&quot;,</span><br><span class="line">  &quot;dev:watch&quot;: &quot;run-p dev:server-run init:watch&quot;,</span><br><span class="line">  &quot;dev&quot;: &quot;run-s init dev:watch&quot;,</span><br><span class="line">  &quot;dev:server-run&quot;: &quot;nodemon build/bundle.js&quot;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure> 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/npm%E3%80%81script/" rel="tag">npm、script</a></li></ul>

    </footer>
  </div>

   
    
</article>

    
    <article
  id="post-css-in-js"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2022/01/11/css-in-js/"
    >css-in-js</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/01/11/css-in-js/" class="article-date">
  <time datetime="2022-01-11T06:52:55.000Z" itemprop="datePublished">2022-01-11</time>
</a>    
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <h1 id="emotion-库学习"><a href="#emotion-库学习" class="headerlink" title="emotion 库学习"></a>emotion 库学习</h1><p>npm 上介绍 <code>emotion 是下一代 css-in-js 的生成器</code>。</p>
<h2 id="css-in-js"><a href="#css-in-js" class="headerlink" title="css-in-js"></a>css-in-js</h2><p>在 web 项目中通过单独引入样式文件为页面上元素添加样式时，css 可能存在以下的局限性：</p>
<ol>
<li>样式在全局作用域内生效，加大了为元素添加独一无二的类名的难度</li>
<li>组件可移植难度加大。移植时除过 js 文件，还要同步移植 css 样式文件</li>
<li>对于动态的样式支持复杂。</li>
</ol>
<p>为了解决这些问题，web 项目中出现了 css-in-js 方案，它是 web 项目中将 css 代码捆绑在 js 中的解决方案，其主要目的：</p>
<ol>
<li>增强代码可移植性</li>
<li>设置样式为组件作用域</li>
<li>方便为组件添加动态样式</li>
</ol>
<p>但由于将 css 揉在了 js 中，不可避免的会出现以下问题：</p>
<ol>
<li>代码的可读性降低</li>
<li>项目复杂度增强</li>
</ol>
<p>所以对于 css-in-js 方案要根据项目合理选择。<code>emotion</code> 是 css-in-js 方案下产生的第三方库，在使用 css-in-js 方案时，可借助 emotion 库，方便快捷的实现需求。</p>
<h2 id="emotion-库"><a href="#emotion-库" class="headerlink" title="emotion 库"></a>emotion 库</h2><p>详细文档可参考 <a target="_blank" rel="noopener" href="https://emotion.sh/docs/introduction">https://emotion.sh/docs/introduction</a>。</p>
<h3 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h3><p><code>There are two primary methods of using Emotion. The first is framework agnostic and the second is for use with React.</code></p>
<p>在项目中使用 emotion 的两种方式：</p>
<ol>
<li>单独使用，不配合框架<ol>
<li><code>@emotion/css</code></li>
</ol>
</li>
<li>配合 react 框架使用<ol>
<li><code>@emotion/react</code></li>
<li>注意 jsx 语法在执行时不能转为默认 <code>React.createElement()</code>，需要转为 <code>jsx()</code> </li>
</ol>
</li>
</ol>
<h3 id="配合-react-框架使用"><a href="#配合-react-框架使用" class="headerlink" title="配合 react 框架使用"></a>配合 react 框架使用</h3><p>emotion 的使用主要分两大类：</p>
<ol>
<li>css 属性 </li>
<li>styled component 借助 <code>@emotion/styled</code> 实现。 <code>styled is a way to create React components that have styles attached to them</code></li>
</ol>
<h4 id="css-属性"><a href="#css-属性" class="headerlink" title="css 属性"></a>css 属性</h4><p>使用 css prop 属性前转换语法的两种方式：</p>
<ol>
<li>babel preset</li>
<li>jsx pragma</li>
</ol>
<p><code>After adding the preset or setting the pragma as a comment, compiled jsx code will use emotion’s jsx function instead of React.createElement.</code></p>
<p>添加 css 属性步骤：</p>
<ol>
<li>设置 babel 或者 jsx pragma</li>
<li>css 可接收 object styles 和 string styles<ol>
<li>object styles 不需要任何导入</li>
<li>string styles 需要使用从 <code>@emotion/react</code> 中导入的 <code>css</code> 函数</li>
</ol>
</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** <span class="doctag">@jsxRuntime </span>classic */</span></span><br><span class="line"><span class="comment">/** <span class="doctag">@jsx </span>jsx */</span> </span><br><span class="line"><span class="keyword">import</span> &#123; jsx, css &#125; <span class="keyword">from</span> <span class="string">&#x27;@emotion/react&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 对象形式</span></span><br><span class="line"><span class="keyword">const</span> myLabelCss = css(&#123;</span><br><span class="line">  display: <span class="string">&#x27;block&#x27;</span>,</span><br><span class="line">  fontWeight: <span class="string">&#x27;bold&#x27;</span>,</span><br><span class="line">  fontSize: <span class="string">&#x27;14px&#x27;</span></span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// 字符串形式</span></span><br><span class="line"><span class="keyword">const</span> myInputCss = css`</span><br><span class="line"><span class="css">  <span class="attribute">display</span>: block;</span></span><br><span class="line"><span class="css">  <span class="attribute">border-radius</span>: <span class="number">2px</span>;</span></span><br><span class="line"><span class="css">  <span class="attribute">margin</span>: <span class="number">3px</span> <span class="number">0px</span> <span class="number">5px</span>;</span></span><br><span class="line"><span class="css">`</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">MyTextInput</span>(<span class="params">&#123;label, ...props&#125;</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> [field, meta] = useField(props);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;&gt;</span><br><span class="line">      &lt;label css=&#123;myLabelCss&#125; htmlFor=&#123;props.id || props.name&#125;&gt;&#123;label&#125;&lt;/label&gt;</span><br><span class="line">      &lt;input css=&#123;myInputCss&#125; &#123;...field&#125; &#123;...props&#125; /&gt;</span><br><span class="line">    &lt;/&gt;</span><br><span class="line">  )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>myInputCss 和 myLabelCss</code> 的值主要内容如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(myLabelCss);</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">&quot;name&quot;</span>: <span class="string">&quot;1bf27r4&quot;</span>,</span><br><span class="line">    <span class="string">&quot;styles&quot;</span>: <span class="string">&quot;display:block;font-weight:bold;font-size:14px;&quot;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(myInputCss);</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">&quot;name&quot;</span>: <span class="string">&quot;1hkb5h9&quot;</span>,</span><br><span class="line">    <span class="string">&quot;styles&quot;</span>: <span class="string">&quot;\n  display: block;\n  border-radius: 2px;\n  margin: 3px 0px 5px;\n&quot;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>页面展示效果如图：<br><img src="/2022/01/11/css-in-js/css.png" alt="效果图"></p>
<h4 id="Styled-Components"><a href="#Styled-Components" class="headerlink" title="Styled Components"></a>Styled Components</h4><ol>
<li>引入  <code>@emotion/styled</code></li>
<li>支持以字符串和对象两种形式动态设置样式。具体设置过程如下:</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> styled <span class="keyword">from</span> <span class="string">&#x27;@emotion/styled&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 对象形式动态设置样式</span></span><br><span class="line"><span class="keyword">const</span> Button = styled.button(&#123;</span><br><span class="line">  padding: <span class="string">&#x27;2px 5px 3px&#x27;</span>,</span><br><span class="line">  display: <span class="string">&#x27;block&#x27;</span>,</span><br><span class="line">  color: <span class="string">&#x27;black&#x27;</span>,</span><br><span class="line">&#125;, <span class="function"><span class="params">props</span> =&gt;</span> (&#123;</span><br><span class="line">  color: props.color</span><br><span class="line">&#125;));</span><br><span class="line"><span class="comment">// 动态设置样式2</span></span><br><span class="line"><span class="keyword">const</span> ButtonCopy = styled.button(<span class="function"><span class="params">props</span> =&gt;</span> (&#123;</span><br><span class="line">  padding: <span class="string">&#x27;2px 5px 3px&#x27;</span>,</span><br><span class="line">  display: <span class="string">&#x27;block&#x27;</span>,</span><br><span class="line">  color: props.color || <span class="string">&#x27;black&#x27;</span>,</span><br><span class="line">&#125;));</span><br><span class="line"><span class="comment">// 字符串形式动态设置样式</span></span><br><span class="line"><span class="keyword">const</span> ErrorMsg = styled.div<span class="string">`</span></span><br><span class="line"><span class="string">  color: <span class="subst">$&#123;props =&gt; props.color || <span class="string">&#x27;red&#x27;</span>&#125;</span>;</span></span><br><span class="line"><span class="string">  font-size: 12px;</span></span><br><span class="line"><span class="string">`</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">MyTextInput</span>(<span class="params">&#123;label, ...props&#125;</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> [field, meta] = useField(props);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;&gt;</span><br><span class="line">      &lt;label htmlFor=&#123;props.id || props.name&#125;&gt;&#123;label&#125;&lt;/label&gt;</span><br><span class="line">      &lt;input &#123;...field&#125; &#123;...props&#125; /&gt;</span><br><span class="line">      &#123;</span><br><span class="line">        meta.touched &amp;&amp; meta.error </span><br><span class="line">          ? <span class="xml"><span class="tag">&lt;<span class="name">ErrorMsg</span>&gt;</span>&#123;meta.error&#125;<span class="tag">&lt;/<span class="name">ErrorMsg</span>&gt;</span></span></span><br><span class="line">          : <span class="literal">null</span></span><br><span class="line">      &#125;</span><br><span class="line">    &lt;/&gt;</span><br><span class="line">  )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure> 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/css-in-js%E3%80%81emotion/" rel="tag">css-in-js、emotion</a></li></ul>

    </footer>
  </div>

   
    
</article>

    
    <article
  id="post-进程与线程整理"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2022/01/10/%E8%BF%9B%E7%A8%8B%E4%B8%8E%E7%BA%BF%E7%A8%8B%E6%95%B4%E7%90%86/"
    >进程与线程整理</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/01/10/%E8%BF%9B%E7%A8%8B%E4%B8%8E%E7%BA%BF%E7%A8%8B%E6%95%B4%E7%90%86/" class="article-date">
  <time datetime="2022-01-10T09:29:23.000Z" itemprop="datePublished">2022-01-10</time>
</a>    
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <p><img src="/2022/01/10/%E8%BF%9B%E7%A8%8B%E4%B8%8E%E7%BA%BF%E7%A8%8B%E6%95%B4%E7%90%86/xiaofujun.png" alt="进程与线程思维导图"></p> 
      <a class="article-more-link" href="/2022/01/10/%E8%BF%9B%E7%A8%8B%E4%B8%8E%E7%BA%BF%E7%A8%8B%E6%95%B4%E7%90%86/"
        >继续阅读</a
      >
       
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/event-loop/" rel="tag">event loop</a></li></ul>

    </footer>
  </div>

   
    
</article>

    
    <article
  id="post-formik-学习笔记"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2022/01/07/formik-%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/"
    >formik 学习笔记</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/01/07/formik-%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" class="article-date">
  <time datetime="2022-01-07T06:43:54.000Z" itemprop="datePublished">2022-01-07</time>
</a>    
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <h1 id="Formik-库"><a href="#Formik-库" class="headerlink" title="Formik 库"></a>Formik 库</h1><p><code>ForMik</code> 是一个小型的库，主要配合 react 生成 form，处理 form 相关的事件。其主要可以解决以下三个和 form 相关的问题：</p>
<ol>
<li>简化获取设置 form 表单的数据状态</li>
<li>简化校验和显示校验结果的状态</li>
<li>简化解决 form 表单的提交</li>
</ol>
<p>附上官方文档的地址：<a target="_blank" rel="noopener" href="https://formik.bootcss.com/">https://formik.bootcss.com/</a></p>
<h2 id="Formik-使用"><a href="#Formik-使用" class="headerlink" title="Formik 使用"></a>Formik 使用</h2><p>Formik 提供了 <code>react hook</code> 以及 <code>React 组件</code>。所以在类组件和函数组件中都可以使用 Formik。</p>
<h3 id="useFormik"><a href="#useFormik" class="headerlink" title="useFormik()"></a>useFormik()</h3><p><code>useFormik()</code> 钩子可设置 form 的初始值状态以及表单相关的提交事件等。该钩子返回值是一个对象，对象中包含 form 相关的状态以及提交等事件的处理函数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  initialValues: &#123;&#125;,</span><br><span class="line">  validationSchema: &#123;&#125;,</span><br><span class="line">  onSubmit: <span class="function">(<span class="params">values</span>) =&gt;</span> &#123;&#125;,</span><br><span class="line">  validate: <span class="function">(<span class="params">values</span>) =&gt;</span> &#123;<span class="keyword">return</span> errors&#125;,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="validation"><a href="#validation" class="headerlink" title="validation"></a>validation</h3><p>Formik 提供了 form 提交前的校验功能。但是其校验也有一定的局限：</p>
<ol>
<li>不支持在 react native 中使用</li>
<li>不支持自定义校验失败的提示信息</li>
<li>校验过程笨拙</li>
</ol>
<p>触发校验的时机：</p>
<ol>
<li>onChange 事件</li>
<li>input 输入框失去焦点后</li>
<li>点击提交按钮时，如果校验不通过，则不提交</li>
</ol>
<p>由于触发时机很多，大多数情况下，我们只想在用户输入完该字段后显示该字段的错误消息，为了优化显示校验失败的提示信息需要满足以下几点：</p>
<ol>
<li><code>formik.errors.username</code> 有值</li>
<li>用户输入过，且输入完毕，即失去焦点时校验显示错误信息</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  formik.touched.username &amp;&amp; formik.errors.username ? <span class="string">&#x27;显示错误信息&#x27;</span> : <span class="literal">null</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>由于通过 <code>validate</code> 属性进行 form 的校验存在局限性，所以 formik 官方推荐使用 <code>validationSchema</code>属性配合 <code>yup</code> 库实现 form 的校验。schema 即定义数据的类型。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">validationSchema: Yup.object(&#123;</span><br><span class="line">  username: Yup.string()</span><br><span class="line">    .max(<span class="number">15</span>, <span class="string">&#x27;Must be 15 characters or less&#x27;</span>)</span><br><span class="line">    .required(<span class="string">&#x27;Required&#x27;</span>),</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="getFieldProps"><a href="#getFieldProps" class="headerlink" title="getFieldProps()"></a>getFieldProps()</h3><p>使用 Formik 构建表单的好处之一即可减少样本代码。其具体可通过 <code>getFieldProps</code> 实现，可减少重现书写 <code>onChange  onBlur value checked</code> 属性。但这仅仅只是优化了一部分样本代码，对于每个 input 输入框我们还是需要手动添加 <code>getFieldProps</code> 属性。为了彻底简化书写，使代码更简洁， Formik 通过 react context component。其实现原理如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> FormikContext = React.createContext();</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Formik</span>(<span class="params">&#123;children, ...props&#125;</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> formikStateAndHelpers = useFormik(props);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;FormikContext.Provider value=&#123;formikStateAndHelpers&#125;&gt;</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="keyword">typeof</span> children === <span class="string">&quot;function&quot;</span></span><br><span class="line">          ? children(formikStateAndHelpers)</span><br><span class="line">          : children</span><br><span class="line">      &#125;</span><br><span class="line">    &lt;/FormikContext.Provider&gt;</span><br><span class="line">  )</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><code>&lt;Formik /&gt;, &lt;Form /&gt;, &lt;Field /&gt;, and &lt;ErrorMessage /&gt;</code> 可以获取父组件 <code>&lt;Formik /&gt;</code> 的 state 和 method。</p>
<h3 id><a href="#" class="headerlink" title></a><Field></Field></h3><p>Field 组件默认渲染为 input 输入框。其可设置的 API 如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">name: <span class="string">&#x27;必须要有的属性，定义当前的 id&#x27;</span>,</span><br><span class="line">className: <span class="string">&#x27;类名称&#x27;</span>,</span><br><span class="line">placeholder: <span class="string">&#x27;提示信息&#x27;</span>,</span><br><span class="line"><span class="keyword">as</span>: <span class="string">&#x27;select | textarea&#x27;</span>, <span class="comment">// 不设置默认 input，</span></span><br></pre></td></tr></table></figure>

<p>由于 Formik 的 <Field> 默认只支持 input/select/textarea 三种形式的展示，所以下面根据开发需要自定义一些 form 输入组件。</Field></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">MyCheckboxField</span> (<span class="params">&#123;label, ...props&#125;</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> [field, meta] = useField(props);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;&gt;</span><br><span class="line">      &lt;input &#123;...field&#125; &#123;...props&#125; type=<span class="string">&quot;checkbox&quot;</span> /&gt;</span><br><span class="line">      &lt;label htmlFor=&#123;props.id || props.name&#125;&gt;&#123;label&#125;&lt;/label&gt;</span><br><span class="line">      &#123;</span><br><span class="line">        meta.touched &amp;&amp; meta.error </span><br><span class="line">          ? <span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>&#123;meta.error&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">          : <span class="literal">null</span></span><br><span class="line">      &#125;</span><br><span class="line">    &lt;/&gt;</span><br><span class="line">  )</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>


<h2 id="开发中使用-Formik-优点"><a href="#开发中使用-Formik-优点" class="headerlink" title="开发中使用 Formik 优点"></a>开发中使用 Formik 优点</h2><ol>
<li>减少样本代码：例如 onChange,onBlur 等</li>
<li>提供一些内置组件，更快的搭建 UI。例如：<code>&lt;Form/&gt; &lt;Field /&gt;&lt;ErrorMessage /&gt;</code></li>
<li>提供 form 校验管理工具</li>
</ol>
<h2 id="配合使用的第三方工具"><a href="#配合使用的第三方工具" class="headerlink" title="配合使用的第三方工具"></a>配合使用的第三方工具</h2><ol>
<li>借助 Yup 工具实现 form 校验 </li>
</ol>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/formik%E3%80%81react%E3%80%81form/" rel="tag">formik、react、form</a></li></ul>

    </footer>
  </div>

   
    
</article>

    
  </article>
  

  
  <nav class="page-nav">
    
    <a class="extend prev" rel="prev" href="/">上一页</a><a class="page-number" href="/">1</a><span class="page-number current">2</span><a class="page-number" href="/page/3/">3</a><a class="page-number" href="/page/4/">4</a><a class="extend next" rel="next" href="/page/3/">下一页</a>
  </nav>
  
</section>
</div>

      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2022
        <i class="ri-heart-fill heart_icon"></i> 小付君
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="君书"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->

<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    

  </div>
</body>

</html>